<template>
  <main class="container">
    <!-- 功能 -->
    <div class="extra">
      <div class="extra-left">
        <a-button type="primary" @click="open = true">新增用户</a-button>
        <a-button @click="uploadBatchUser">批量导入</a-button>
      </div>
      <div class="extra-right">
        <a-input-search
          v-model:value="searchForm.keyword"
          placeholder="请输入姓名或学号"
          style="width: 200px"
          @search="onSearch"
        />
      </div>
    </div>
    <!-- 表格 -->
    <a-table :columns="columns" :data-source="list" :pagination="false" :loading="loading">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key == 'created_at'">{{ formatUnixTimestamp(record.created_at) }}</template>
        <template v-if="column.key == 'updated_at'">{{ formatUnixTimestamp(record.updated_at) }}</template>
        <template v-if="column.key === 'operation'">
          <span class="actions">
            <!-- 编辑 -->
            <FormOutlined @click="updateUser(record._id)" />
            <!-- 删除 -->
            <a-popconfirm title="确定要删除当前用户吗?" ok-text="确定" cancel-text="取消" @confirm="deleteUser(record._id)">
              <DeleteOutlined style="margin-left: 16px; color: red" />
            </a-popconfirm>
          </span>
        </template>
        <template v-if="column.key === 'roles'">
          <a-tag v-for="(role, i) in record.roles" :key="i">{{ role }}</a-tag>
        </template>
      </template>
    </a-table>
    <!-- 分页器 -->
    <a-pagination
      v-model:current="curPage"
      v-model:pageSize="pageSize"
      show-size-changer
      :total="total"
      :show-total="(total: number) => `共 ${total} 条数据`"
    />
  </main>
  <!-- 对话框 -->
  <a-modal
    v-model:open="open"
    :title="`${!editId ? '新增' : '编辑'}用户`"
    :footer="null"
    :destroy-on-close="true"
    @cancel="handleCancel"
  >
    <UserForm @submit="handleSubmit" ref="formRef" />
  </a-modal>
</template>
<script setup lang="ts">
import { notification, type TableColumnsType } from "ant-design-vue"
import usePagination from "@/hooks/usePagination"
import { FormOutlined, DeleteOutlined } from "@ant-design/icons-vue"
import { reactive, ref, nextTick } from "vue"
import UserForm from "./components/user-form.vue"
import { formatUnixTimestamp } from "@/utils"
import {
  getUserList,
  addUser,
  updateUser as updateUserRecord,
  getUserInfoById,
  deleteUser as deleteUserRecord
} from "@/api/user/index"

const searchForm = reactive({
  keyword: ""
})
const formRef = ref()
let editId = ref<string>("")
const open = ref<boolean>(false)
let { curPage, total, pageSize, list, updateData, searchQuery, loading } = usePagination(getUserList)

const columns: TableColumnsType = [
  {
    title: "账号",
    width: 100,
    dataIndex: "username",
    key: "username",
    align: "center",
    sorter: { compare: (a: any, b: any) => a.name.localeCompare(b.name) }
  },
  {
    title: "真实姓名",
    width: 120,
    dataIndex: "name",
    key: "name",
    align: "center",
    sorter: { compare: (a: any, b: any) => a.name.localeCompare(b.name) }
  },
  { title: "角色", dataIndex: "roles", key: "roles", align: "center" },
  {
    title: "备注",
    dataIndex: "desc",
    key: "desc",
    align: "center",
    sorter: { compare: (a: any, b: any) => a.name.localeCompare(b.name) }
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    key: "created_at",
    align: "center",
    sorter: { compare: (a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime() }
  },
  {
    title: "更新时间",
    dataIndex: "updated_at",
    key: "updated_at",
    align: "center",
    sorter: { compare: (a: any, b: any) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime() }
  },

  {
    key: "operation",
    fixed: "right",
    width: 100
  }
]

const onSearch = () => {
  if (!searchForm.keyword) {
    if (searchQuery.username) delete searchQuery.username
    if (searchQuery.studentId) delete searchQuery.studentId
    updateData()
    return
  }
  // 判断输入的关键字是否为纯数字，如果是，则认为是学号
  if (/^\d+$/.test(searchForm.keyword)) {
    // 根据学号查询
    if (searchQuery.username) delete searchQuery.username
    searchQuery.studentId = searchForm.keyword
  } else {
    // 否则，认为是姓名
    // 根据姓名查询数据库
    if (searchQuery.studentId) delete searchQuery.studentId
    searchQuery.username = searchForm.keyword
  }
}

const handleSubmit = async (values: any) => {
  if (!editId.value) {
    // 新增用户
    let { code, message } = await addUser(values)
    notification.open({
      type: code == 0 ? "success" : "error",
      message
    })
  } else {
    let data = await updateUserRecord(editId.value, values)
    if (data.code == 0) {
      notification.success({
        message: data.message
      })
    }
  }
  updateData()
  open.value = false
}
const updateUser = async (userId: string) => {
  editId.value = userId
  let { data: userInfo } = await getUserInfoById(userId)
  open.value = true
  nextTick(() => {
    //回填数据
    formRef.value.showPasswordItem = false
    formRef.value.formState.username = userInfo!.username
    formRef.value.formState.name = userInfo!.name
    formRef.value.formState.roles = userInfo!.roles
    formRef.value.formState.desc = userInfo!.desc
  })
}
const uploadBatchUser = () => {
  notification.warning({
    message: "功能暂未开放",
    description: "批量上传功能暂不可用，后续将陆续开放！"
  })
}
const handleCancel = () => {
  editId.value = ""
}
const deleteUser = async (userId: string) => {
  let data = await deleteUserRecord(userId)
  if (data.code == 0) {
    notification.success({
      message: data.message
    })
    updateData()
  }
}
</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
